#include "Logger.h"
#include <time.h>

std::ofstream* Logger::ofs = NULL;
int Logger::reportingLevel = Log::DEBUG;
std::string Logger::levelNames[] = {
    "ERROR",
    "WARNING",
    "INFO",
    "DEBUG",
    "DEBUG1",
    "DEBUG2",
    "DEBUG3",
    "DEBUG4"
};

// TODO: Fix the commenting in here

int& Logger::ReportingLevel()
{
    return reportingLevel;
}

void Logger::init(int repLevel, std::string filename)
{
    reportingLevel = repLevel;

    if (ofs != NULL)
    {
        ofs->close();
        delete ofs;
        ofs = NULL;
    }

    if (!filename.empty())
    {
        ofs = new std::ofstream;
        ofs->open(filename.c_str());
    }
}

void Logger::shutdown()
{
    if (ofs != NULL)
    {
        ofs->close();
        delete ofs;
        ofs = NULL;
    }
}

void printCurrentTime(std::ostringstream& dest)
{
    time_t rawtime;
    struct tm * timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    static char timeBuf[256];

    // time format:
    // mm/dd/yyyy hh:mm:ss
    sprintf(timeBuf, "%02d/%02d/%04d %02d:%02d:%02d", timeinfo->tm_mon, timeinfo->tm_mday, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);

    dest << timeBuf;
}

std::ostringstream& Logger::Get(int level)
{
    //std::cout << "Entered logger get at level " << level <<  "\n";
    //time_t rawtime;
    //time ( &rawtime );
    //os << ctime(&rawtime);
    printCurrentTime(os);
    //std::cout << "A\n";
    os << " " << levelNames[level] << ": ";
    //std::cout << "B\n";
    os << std::string(level > Log::DEBUG ? level - Log::DEBUG : 0, '\t');
    //std::cout << "D\n";
    messageLevel = level;
    //std::cout << "About to leave logger get...\n";
    return os;
}

Logger::Logger()
{
}

Logger::~Logger()
{
    os << std::endl;

    if (ofs != NULL)
    {
        (*ofs) << os.str();
        ofs->flush();
    }

    if (messageLevel < Log::DEBUG)
    {
        std::cout << os.str();
    }
}
